// master.js
const cluster = require('cluster');
const cpus = require("os").cpus();
const logger = require("./logger.js");
const http = require('http');
const Worker = require('./worker');

/** 进程名 */
process.title = "node-master";
/** 进程Map */
const workers = {};

/** 创建子进程 */
function createServer() {
  // 生成进程
  const worker = cluster.fork();
  // 监听子进程消息
  worker.on('message', function (message) {
    // 异常终止时，重新创建worker
    if (message.act === "suicide") {
      logger.log(`Worker [${worker.pid}] 异常终止`);
      createWorker();
    }
    // 发送默认消息
    worker.send('master知道了');
  });
  //worker结束
  worker.on("exit", function (code, signal) {
    delete workers[worker.pid];
  });
  // 缓存
  worker[worker.pid] = worker;
  // 返回子进程
  return worker;
}

// 当是主进程时
if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // 策略一：一种轮询的策略，默认值
  cluster.schedulingPolicy = cluster.SCHED_RR;

  // cpus创建
  for (let i = 0; i < cpus.length - 1; i++) {
    createServer();
  }
  // 监听退出
  cluster.on('exit', (worker, code, signal) => {
    console.log("worker process exited, code: %s signal: %s", code, signal);
  });

  // 主进程收到退出信号时，kill子进程
  process.once("SIGINT", close.bind(this, "SIGINT")); // kill(2) Ctrl-C
  process.once("SIGQUIT", close.bind(this, "SIGQUIT")); // kill(3) Ctrl-\
  process.once("SIGTERM", close.bind(this, "SIGTERM")); // kill(15) default
  process.once("exit", close.bind(this));
  // 关闭子进程
  function close(code) {
    logger.log(`主进程退出: ${code}`);
    if (code !== 0) {
      for (let pid in workers) {
        console.log("master process exited, kill worker pid: ", pid);
        logger.log(`杀死子进程！${pid}`, code);
        workers[pid].kill("SIGINT");
      }
    }
    process.exit(0);
  }

} else {
  Worker(7000);
}